package com.bw.common.view

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.view.BaseFragment
import com.bw.common.entity.CustomEvent
import com.bw.common.vm.BaseViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.reflect.ParameterizedType

abstract class BaseMvvmFragment<VDB:ViewDataBinding,VM:BaseViewModel>: BaseFragment<VDB>() {


    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    //直接通过泛型拿到对应的ViewModel的class,来进行实例化
    protected val vm: VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }
    open fun onError(t: Throwable) {
        ToastUtils.showLong(t.message)
        Log.e("TagA", "error:${t.message}")
        t.printStackTrace()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        vm.onFailed.observe(requireActivity(), ::onError)
        super.onViewCreated(view, savedInstanceState)
        //注册EventBus事件总线
        EventBus.getDefault().register(this)
    }

    /**
     * EventBus接收事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onReceiveEvent(event: CustomEvent?){
        if (event != null && event.target == this.javaClass.simpleName){
            handEvent(event)
        }
    }

    protected open fun handEvent(event: CustomEvent){

    }


    override fun onDestroyView(){
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }




}